_Pragma("once");

#include "Workable.h"
#include "HttpCommunicator.h"
#include "SafeDataFile.h"
#include"SingletonTemplate.h"

class FileDownloader : public Workable<FileDownloader> {
    using FinishCallback = std::function<bool (FileDownloader&, const std::string& pathname)>;

    friend class SingletonTemplate<FileDownloader>;

    static constexpr int MAX_RETRY_COUNT = 12;

public:
    /** Default destructor */
    ~FileDownloader();


    bool initial()  {
        mdownloaded = 0;
        header.fileName = mpathname;//DOWNLOAD_PATHNAME;
        return true;
    }

    bool uninitial()  {
        retryCount = MAX_RETRY_COUNT;
        header.reset();

        return true;
    }

    bool doWork();

    /** Default constructor */
    FileDownloader();

    void initialize(const UriInfo& urlInfo, const std::string& pathname, const FinishCallback& finishCallback){
        muriInfo = urlInfo;
        mpathname = pathname;

        mfinishCallback = finishCallback;
    }

protected:

    ssize_t download(HttpHeader header);
    void printProgress(const char *fileName, ssize_t sum, ssize_t fileSize);

    int retryCount = MAX_RETRY_COUNT;
    ssize_t mdownloaded;
    HttpHeader header;
    HttpCommunicator mhttpCommunictor;
    std::string mpathname;

    FinishCallback mfinishCallback;

    UriInfo muriInfo{"112.74.202.10", 8081, "http:", "/download/update.tar.gz"};// http://192.168.1.100:8081/pavt/5.DOWNLOAD/xiao/update.tar.gz
//"112.74.202.10:8081/download/rootfs_cpp.tar.gz"
};


using FileDownloaderPtr = std::shared_ptr<FileDownloader>;



